<template>
  <basic-container>
    <el-row>
      <el-text>所属产品：</el-text>
      <el-select v-model="productKey" placeholder="请选择产品" filterable clearable @change="productChange"
                 class="margin-node"
                 style="width: 200px">
        <el-option
          v-for="item in productSelect"
          :key="item.productKey"
          :label="item.productName"
          :value="item.productKey">
        </el-option>
      </el-select>
      <el-text class="margin-node">查询设备：</el-text>
      <avue-input-table :props="deviceProps"
                        :children="deviceChildren"
                        :formatter="deviceFormatter"
                        :on-load="onLoadDevice"
                        v-model="deviceId"
                        placeholder="请选择设备" style="width: 200px">
      </avue-input-table>
      <el-button :loading="loading" :disabled="this.isConnected" type="primary" class="margin-node"
                 @click="onConnect">开启日志
      </el-button>
      <el-button :disabled="!this.isConnected" plain type="danger" class="margin-node"
                 @click="disConnect">关闭日志
      </el-button>
      <el-button @click="openTsl">物模型 TSL</el-button>
    </el-row>
    <el-row>
      <el-dialog v-model="visibleTsl" :before-close="beforeCloseTsl" title="物模型" width="600">
        <el-row>
          <el-alert
            title="物模型是云端对设备功能的抽象描述，涵盖了设备的属性、服务和事件。物联网平台通过物的描述语言，即 TSL（Thing Specification Language），以 JSON 格式表达这一模型。开发者可以利用 TSL 构建并上报设备数据。完整的物模型可用于云端应用的开发，而精简版的物模型则可结合设备端SDK用于设备的开发工作。"
            type="info" :closable="false" />
        </el-row>
        <el-row>
          <el-select
            v-model="blockId"
            clearable
            placeholder="请选择模块"
            @change="blockTslChange"
            style="width: 240px"
          >
            <el-option
              v-for="item in dataBlock"
              :key="item.id"
              :label="item.isDefault === 1 ? '默认模块': item.blockName"
              :value="item.id"
            />
          </el-select>
        </el-row>
        <el-row>
          <code-editor v-model="tsl" :json="true" :readonly="true" theme="nord" />
        </el-row>
      </el-dialog>
    </el-row>
    <el-row v-if="this.isConnected">
      <el-col :span="24">
        <el-tabs v-model="activeName" tab-position="left" type="border-card">
          <el-tab-pane label="物模型日志" name="tsl">
            <device-function :product-key="this.productKey" :device-id="this.deviceId"></device-function>
          </el-tab-pane>
          <el-tab-pane label="设备日志" name="log">
            <device-log :product-key="this.productKey" :device-id="this.deviceId" :device-name="this.deviceName"></device-log>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <el-row v-if="!this.isConnected">
      <el-col :span="24">
        <el-result title="设备日志库"
                   sub-title="设备日志库可随时查看每一台设备的属性、命令、事件等总览的日志信息">
          <template #icon>
            <el-image style="width: 200px; height: 200px" src="/svg/icon4.svg" />
          </template>
          <template #extra>
            <el-row>
              <el-alert type="info" show-icon :closable='false'>
                <template #title>
                  <el-text size="small">设备日志仅可查看特定设备的日志信息，若需要查看设备的其他信息请移步</el-text>
                  <el-text size="small" type="primary" class="cursor" @click="viewDevice"> 设备管理</el-text>
                </template>
              </el-alert>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-button type="primary" @click="onConnect()">开启设备日志库</el-button>
              </el-col>
            </el-row>
          </template>
        </el-result>
      </el-col>
    </el-row>
  </basic-container>
</template>
<script>
import { select as selectProduct } from '@/api/iot/product';
import { getDetail as getDeviceDetail, getList as getDeviceList } from '@/api/iot/device';
import { dataDraftedTsl, dataPublishedByKey, dataPublishedTsl } from '@/api/iot/product/version';
import { validatenull } from '@/utils/validate';
import { mapGetters } from 'vuex';

export default {
  name: 'deviceLogger',
  data() {
    return {
      isConnected: false,
      loading: false,
      visibleTsl: false,
      activeName: 'tsl',
      tsl: '',
      productKey: '',
      productId: '',
      blockId: '',
      dataBlock: [],
      deviceId: '',
      deviceName: '',
      deviceSecret: '',
      deviceProps: {
        label: 'deviceName',
        value: 'id'
      },
      deviceChildren: {
        border: true,
        column: [{
          label: '产品编号',
          prop: 'productKey',
          width: 200
        }, {
          label: '设备名称',
          prop: 'deviceName',
          search: true,
          width: 250
        }, {
          label: '设备密钥',
          prop: 'deviceSecret',
          search: true
        }, {
          label: '唯一编号',
          prop: 'uniqueNo',
          search: true
        }, {
          label: '设备状态',
          prop: 'deviceStatusName',
          width: 120
        }, {
          label: '激活时间',
          prop: 'activeTime',
          width: 180
        }]
      },
      productSelect: {},
      deviceData: {},
      dataSnapshot: {},
    };
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  watch: {
    deviceId() {
      if (!validatenull(this.deviceId)) {
        this.initDevice(this.deviceId);
      }
    }
  },
  created() {
    this.init();
  },
  beforeRouteLeave() {
    this.disConnect();
  },
  methods: {
    init() {
      selectProduct().then(res => {
        this.productSelect = res.data.data;
      });
    },
    initDevice(deviceId) {
      getDeviceDetail(deviceId).then(res => {
        this.deviceData = res.data.data;
        this.deviceName = this.deviceData.deviceName;
        this.deviceSecret = this.deviceData.deviceSecret;
      });
    },
    deviceFormatter(row) {
      if (!row.deviceName) return '';
      return row.deviceName;
    },
    onLoadDevice({ page, value, data }, callback) {
      if (validatenull(this.productKey)) {
        this.$message.warning('请先选择产品');
        callback({
          total: 0,
          data: []
        });
        return;
      }
      let param = {};
      let currentPage = 1;
      let pageSize = 10;
      //首次查询信息
      if (value) {
        getDeviceDetail(value).then(res => {
          callback(res.data.data);
        });
        return;
      }
      if (data) {
        param = data;
      }
      if (page) {
        currentPage = page.currentPage;
        pageSize = page.pageSize;
      }
      //分页查询信息
      getDeviceList(currentPage, pageSize, Object.assign(param, {
        productKey: this.productKey,
      })).then(res => {
        const data = res.data.data;
        callback({
          total: data.total,
          data: data.records
        });
      });
    },
    onConnect() {
      if (validatenull(this.productKey) || validatenull(this.deviceId)) {
        this.$message.warning('请选择产品和设备');
        return;
      }

      this.loading = true;
      // 加载设备快照数据
      this.loadSnapshot(this.productKey);
      this.isConnected = true;
      this.loading = false;

    },
    disConnect() {
      if (this.isConnected) {
        this.isConnected = false;
      }
    },
    productChange(value) {
      if (validatenull(value)) {
        return;
      }
      this.productKey = value;
      this.deviceId = '';
    },
    openTsl() {
      if (!this.isConnected) {
        this.$message.warning('请先开启日志库');
        return;
      }
      // 设置产品ID
      this.productId = this.dataSnapshot.profile.productId;
      // 设置默认模块
      if (validatenull(this.blockId)) {
        this.dataBlock = this.dataSnapshot.blocks;
        const defaultItem = this.dataBlock.find(item => item.isDefault === 1);
        if (!validatenull(defaultItem)) {
          this.blockId = defaultItem.id;
        }
      }
      // 设置物模型
      if (!validatenull(this.productId)) {
        dataPublishedTsl(this.productId, this.blockId).then(res => {
          this.tsl = JSON.stringify(res.data.data);
        });
        this.visibleTsl = true;
      }
    },
    beforeCloseTsl() {
      this.tsl = '';
      this.visibleTsl = false;
    },
    blockTslChange(value) {
      this.blockId = value;
      dataDraftedTsl(this.productId, this.blockId).then(res => {
        this.tsl = JSON.stringify(res.data.data);
      });
    },
    async loadSnapshot(productKey) {
      dataPublishedByKey(productKey).then(res => {
        this.dataSnapshot = res.data.data;
      });
    },
    viewDevice() {
      this.$router.push({
        path: `/iot/device`
      });
    },
  }
};

</script>
<style>
.margin-node {
  margin-left: 12px;
}
</style>
